package com.quyunshuo.module.home.util

import android.annotation.SuppressLint
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.TextStyle
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.TimeZone


const val QRCODE_TIME_FORMAT = "yyyyMMdd'T'HHmmss'Z'"
const val UI_TIME_FORMAT = "yyyy.MM.dd  HH:mm"

/**
 * UTC时间转本地时间
 * @param utcTime eg: 20211021T105725Z
 * @return 时间戳
 */
fun utcTimeToLocalTime(utcTime: String?): Long {
    if (utcTime.isNullOrBlank()) {
        return 0
    }

    val dateFormat = SimpleDateFormat(QRCODE_TIME_FORMAT, Locale.getDefault())

    try {
        return dateFormat.parse(utcTime)!!.time + getLocalZoneWithTimeZoneDifference()
    } catch (e: Exception) {
        print(e)
    }
    return 0
}


/**
 * UTC时间转本地时间
 * @param date
 * @return 二维码时间的数据格式
 */
fun local2UTC(date: Date): String {
    val sdf = SimpleDateFormat(QRCODE_TIME_FORMAT, Locale.getDefault())
    sdf.timeZone = TimeZone.getTimeZone("UTC")
    return sdf.format(date)
}

/**
 * @param time UTC时间
 * @return UI上需要展示的时间格式 eg：2021.09.12 19:00
 */
fun uiTimeFormat(time: String): String {
    val dateFormat = SimpleDateFormat(QRCODE_TIME_FORMAT, Locale.getDefault())
    val uiFormat = SimpleDateFormat(UI_TIME_FORMAT, Locale.getDefault())

    try {
        val timeTemp = dateFormat.parse(time)!!.time + getLocalZoneWithTimeZoneDifference()
        return uiFormat.format(Date(timeTemp))
    } catch (e: Exception) {
        print(e)
    }
    return ""
}

fun getHourOfDate(time: String): String {
    val dateFormat = SimpleDateFormat(QRCODE_TIME_FORMAT, Locale.getDefault())
    val uiFormat = SimpleDateFormat("HH:mm", Locale.getDefault())

    try {
        val timeTemp = dateFormat.parse(time)!!.time + getLocalZoneWithTimeZoneDifference()
        return uiFormat.format(Date(timeTemp))
    } catch (e: Exception) {
        print(e)
    }
    return ""
}

/**
 * 获取当前时区去零时区的时间差值
 */
fun getLocalZoneWithTimeZoneDifference(): Long {
    val cal = Calendar.getInstance()
    val offset = cal[Calendar.ZONE_OFFSET]
    cal.add(Calendar.MILLISECOND, -offset)
    val timeStampUTC = cal.timeInMillis
    val timeStamp: Long = Date().time

    return timeStamp - timeStampUTC
}


fun formatTime(start: String?, end: String?): String {
    if (start.isNullOrBlank() || end.isNullOrBlank()) return ""
    return if (utcTimeToLocalTime(end) - utcTimeToLocalTime(start) >= 1000 * 60 * 60 * 24) {
        // 相隔时间超过一天
        "${uiTimeFormat(start)} - ${uiTimeFormat(end)}"
    } else {
        "${uiTimeFormat(start)}-${getHourOfDate(end)}"
    }
}

@SuppressLint("SimpleDateFormat")
fun convertMonthNumberToString(monthNumber: Int): String {
    val calendar = Calendar.getInstance()
    calendar[Calendar.MONTH] = monthNumber - 1 // 注意月份是从0开始的
    val date = calendar.time
    val sdf = SimpleDateFormat("MMMM")
    return sdf.format(date)
}

fun isToday(date: Date): Boolean {
    val targetDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
    val today = LocalDate.now()
    return targetDate == today
}

fun getMonthName(date: Date, isFull: Boolean = true, locale: Locale = Locale.getDefault()): String {
    val month = date.toInstant()
        .atZone(ZoneId.systemDefault())
        .toLocalDate()
        .month
    return month.getDisplayName(if (isFull) TextStyle.FULL else TextStyle.SHORT, locale)
}

// 处理日期格式化，缓存对象，经常用到避免重复创建
private val dateFormatObjMap = mutableMapOf<String, SimpleDateFormat>()
fun formatDate(regex: String, date: Date): String {
    var dateFormat = dateFormatObjMap[regex]
    if (dateFormat == null) {
        dateFormat = SimpleDateFormat(regex, Locale.getDefault())
        dateFormatObjMap[regex] = dateFormat
    }
    return dateFormat.format(date)
}


fun getDateParts(date: Date): Triple<Int, Int, Int> {
    val localDate = date.toInstant()
        .atZone(ZoneId.systemDefault())
        .toLocalDate() // 提取年月日部分
    val year = localDate.year
    val month = localDate.monthValue
    val day = localDate.dayOfMonth

    return Triple(year, month, day)
}